/**
 * 
 */
package com.seascape.swms.system.service;

import java.util.List;
import java.util.Map;

import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.ImmutableMap;
import com.seascape.swms.conf.PasswordConfig.PasswordEncryptService;
import com.seascape.swms.framework.service.BaseService;
import com.seascape.swms.system.model.Role;
import com.seascape.swms.system.model.User;
import com.seascape.swms.system.model.UserRole;

/**
 * @author Lay
 *
 */
@Service
public class UserService extends BaseService<User>{

	@Autowired
	PasswordEncryptService passwordService;
	
	
	public boolean create(User model) {
		model.setPassword(passwordService.password(model.getPassword()));
		return super.create(model);
	}
	
	public List<Role> queryUsersByRoleId(Integer roleId){
		Map<String,Object> params = ImmutableMap.<String,Object>builder().put("roleId",roleId).build();
		return sqlManager.select("userRole.queryUsersByRoleId", Role.class, params);
	}
	
	public void setRoles(Integer userId,List<Integer> roleIds) {
		Query<UserRole> query = sqlManager.query(UserRole.class).andEq("user_id", userId);
		query.delete();
		for(Integer roleId:roleIds) {
			UserRole userRole = new UserRole();
			userRole.setUserId(userId);
			userRole.setRoleId(roleId);
			sqlManager.insert(userRole, true);
		}
	}
	
}
